package com.longxi.tianjintianbao.ui.base;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.ui.activity.department.DepartmentActivity;
import com.longxi.tianjintianbao.ui.adapter.FullyGridLayoutManager;
import com.longxi.tianjintianbao.ui.adapter.GridImageAdapter;
import com.longxi.tianjintianbao.ui.adapter.GridPersonnelAdapter;
import com.longxi.tianjintianbao.utils.AddPerUtils;
import com.longxi.tianjintianbao.utils.AddPicUtils;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.TimeComparisonUtils;
import com.longxi.tianjintianbao.widget.InputSelectBoxView;
import com.pgyersdk.update.DownloadFileListener;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.pgyersdk.update.javabean.AppBean;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class BasePresenter<V> {

    /*================== 以下是网络请求接口 ==================*/

    public BaseActivity mContext;
    public LazyFragment mFragment;
    public BaseDialogFragment mDialogFragment;

    public AddPicUtils addPicUtils;//选择图片用
    public AddPerUtils addPerUtils;//选择员工用

    public BasePresenter(BaseActivity context) {
        mContext = context;
    }

    public BasePresenter(BaseActivity context, LazyFragment fragment) {
        mContext = context;
        mFragment = fragment;
    }

    public BasePresenter(BaseActivity context, BaseDialogFragment dialogFragment) {
        mContext = context;
        mDialogFragment = dialogFragment;
    }

    protected Reference<V> mViewRef;

    public void attachView(V view) {
        mViewRef = new WeakReference<V>(view);
    }

    public boolean isViewAttached() {
        return mViewRef != null && mViewRef.get() != null;
    }

    public void detachView() {
        if (mViewRef != null) {
            mViewRef.clear();
            mViewRef = null;
        }

//        if (mContext != null) {
//            mContext = null;
//        }
//
//        if (mFragment != null) {
//            mFragment = null;
//        }
//
//        if (mDialogFragment != null) {
//            mDialogFragment = null;
//        }

        if(addPicUtils != null){
            addPicUtils = null;
        }

        if(addPerUtils != null){
            addPerUtils = null;
        }

        dateTime = "";

        MyApplication.unSubscribe(mContext.getLocalClassName());
    }

    public V getView() {
        return mViewRef != null ? mViewRef.get() : null;
    }

    //时间选择哈哈哈

    public void getCurrentDateTime(TextView tvEntryDate, boolean haveTime){
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                tvEntryDate.setText(getTime(date, haveTime));
            }
        }).setSubmitColor(Color.RED)//确定按钮文字颜色
        .setCancelColor(Color.RED)//取消按钮文字颜色
        .setType(new boolean[]{true, true, true, haveTime, haveTime, haveTime}).build();
        pvTime.show();
    }

    public String dateTime = "";
    public void getCurrentDateTimeNoSS(TextView tvEntryDate, boolean haveTime){
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        endDate.set(2099,11,31);
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                dateTime = TimeComparisonUtils.dateTString(date);
                tvEntryDate.setText(dateTime);
            }
        }).setSubmitColor(Color.RED)//确定按钮文字颜色
                .setCancelColor(Color.RED)//取消按钮文字颜色
                .setRangDate(startDate,endDate)//起始终止年月日设定
                .setType(new boolean[]{true, true, true, haveTime, haveTime, false}).build();
        pvTime.show();
    }

    public void getCurrentDateTime(InputSelectBoxView tvEntryDate, boolean haveTime){
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                tvEntryDate.setText(getTime(date, haveTime));
            }
        }).setSubmitColor(Color.RED)//确定按钮文字颜色
                .setCancelColor(Color.RED)//取消按钮文字颜色
                .setType(new boolean[]{true, true, true, haveTime, haveTime, haveTime}).build();
        pvTime.show();
    }

    private String getTime(Date date, boolean haveTime) {//可根据需要自行截取数据显示
        SimpleDateFormat format;
        if(haveTime){
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }else{
            format = new SimpleDateFormat("yyyy-MM-dd");
        }

        return format.format(date);
    }

    //时间选择哈哈哈

    public void getDepartment(boolean isMulti){
        Intent intent = new Intent(MyApplication.getInstance(), DepartmentActivity.class);
        intent.putExtra("isMulti", isMulti);
        mContext.startActivityForResult(intent, AppConst.IntentRequstCode.ACTIVITY_PERSONNEL);
    }

    public void OneButtonDialog(String msg){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setMessage(msg);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }

    /**
     * sp存储
     * @param key
     * @param word
     */
    public void saveSp(String key, String word){
        SharedPreferences sp = MyApplication.getInstance().getSharedPreferences(AppConst.TAG, 0);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(key, word);
        edit.commit();
    }

    public String getSp(String key){
        SharedPreferences pf = MyApplication.getInstance().getSharedPreferences(AppConst.TAG, 0);
        return pf.getString(key, "");
    }

    public GridImageAdapter gridImageAdapter;
    /**
     * 初始化图片选择
     */
    public void initSelectImage(RecyclerView recyclerView, int maxSelectNum){
        addPicUtils = new AddPicUtils(mContext);
        addPicUtils.maxSelectNum = maxSelectNum;
        gridImageAdapter = new GridImageAdapter(mContext, addPicUtils.onAddPicClickListener);
        gridImageAdapter.setList(addPicUtils.selectList);
        gridImageAdapter.setSelectMax(addPicUtils.maxSelectNum);
        recyclerView.setAdapter(gridImageAdapter);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
    }

    public void initTakePicture(RecyclerView recyclerView, int maxSelectNum){
        addPicUtils = new AddPicUtils(mContext);
        addPicUtils.maxSelectNum = maxSelectNum;
        gridImageAdapter = new GridImageAdapter(mContext, addPicUtils.onAddPicIsTakingPictures);
        gridImageAdapter.setList(addPicUtils.selectList);
        gridImageAdapter.setSelectMax(addPicUtils.maxSelectNum);
        recyclerView.setAdapter(gridImageAdapter);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(mContext, 3, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
    }

    public GridPersonnelAdapter gridPersonnelAdapter;
    /**
     * 初始化员工选择
     * @param recyclerView
     */
    public void initSelectPersonnel(RecyclerView recyclerView){
        addPerUtils = new AddPerUtils(mContext);
        gridPersonnelAdapter = new GridPersonnelAdapter(mContext, addPerUtils.onAddPerClickListener);
        gridPersonnelAdapter.setList(addPerUtils.selectList);
        gridPersonnelAdapter.setSelectMax(addPerUtils.maxSelectNum);
        recyclerView.setAdapter(gridPersonnelAdapter);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(mContext, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
    }

    boolean isUpdate = false;

    //检测是否有更新
    public void pgyCheck() {
        AndPermission.with(mContext.getApplication())
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .onGranted(new Action() {
                @Override
                public void onAction(List<String> permissions) {
                    new PgyUpdateManager.Builder().register();
                }
            })
            .onDenied(new Action() {
                @Override
                public void onAction(List<String> permissions) {
                }
            }).start();
    }
}
